package com.changpay.zywy.pay

import android.app.Activity
import com.alipay.sdk.app.PayTask
import com.changpay.zywy.bean.WechatpayBean
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * Created by zhangjiawei on 2017/11/23.
 */

enum class PayHelper {
    INSTANCE;

    private var mPayListener: PayListener? = null

    //h5 直接传支付凭证
    fun weChatPay(context: Activity, orderInfo: WechatpayBean, payListener: PayListener) {
        mPayListener = payListener
        val appId = orderInfo.appid
        val msgApi = WXAPIFactory.createWXAPI(context, appId, false)
        val payReq = PayReq()
        payReq.appId = appId
        payReq.timeStamp = orderInfo.timestamp.toString()
        payReq.prepayId = orderInfo.prepay_id
        payReq.nonceStr = orderInfo.nonce_str
        payReq.partnerId = orderInfo.mch_id
        payReq.sign = orderInfo.sign
        payReq.packageValue = orderInfo.`package`
        msgApi.sendReq(payReq)
    }


    fun aliPay(context: Activity, orderInfo: String, payListener: PayListener) {
        mPayListener = payListener
        val payRunnable = {
            val alipay = PayTask(context)
            val stringStringMap = alipay.payV2(orderInfo, true)
            val payResult = PayResult(stringStringMap)
            val resultStatus = payResult.resultStatus
            context.runOnUiThread { handlerResult(resultStatus) }
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    private fun handlerResult(resultStatus: String) {
        when (resultStatus) {
            "9000"    //支付成功
            -> mPayListener!!.paySuccess("alipay")
            "8000"    //正在处理政，支付结果（有可能支付成功），请查询商户订单列表的支付状态
            -> {
            }
            "4000"    //订单支付失败
            -> mPayListener!!.payFail("alipay", "支付失败：4000")
            "5000"    //重复请求
            -> mPayListener!!.payFail("alipay", "重复请求支付")
            "6001"    //支付取消
            -> mPayListener!!.payCancel("alipay")
            "6002"    //网络连接失败
            -> mPayListener!!.payFail("alipay", "支付失败，网络连接失败，请检查您的网络连接")
            "6004"    //支付结果位未知（有可能支付成功），请查询商户订单列表的支付状态
            -> {
            }
        }
    }

    interface OnPayChoseImpl {
        fun onChoose(type: Int)
    }

    interface DialogStringImpl {
        fun onString(s: String)
    }

    companion object {

        val ALI_PAY = 0
        val WECHAT_PAY = 1
        val BALANCE_PAY = 2
    }
}
